//
//  QTPublicNavigationVC.m
//  QTLifeCircle
//
//  Created by 徐腾 on 2017/1/16.
//  Copyright © 2017年 徐腾. All rights reserved.
//

#import "QTPublicNavigationVC.h"
#import <Masonry.h>
#import "QTLoginViewController.h"

#import "HMCoreDataManager.h"
#import "UserInfo+CoreDataClass.h"

@interface QTPublicNavigationVC ()

//navigation右边的登录按钮
@property (nonatomic,weak) UIButton *rightBtn;

@end

@implementation QTPublicNavigationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNacigationItem) name:@"succeess" object:nil];
    
    [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"top"] forBarMetrics:UIBarMetricsDefault];
    
    //创建右边的按钮
    UIButton *rightButton = [[UIButton alloc] init];
    
    rightButton.tag =100;
    
    [self.navigationBar addSubview:rightButton];
    //设置字体大小
    rightButton.titleLabel.font = [UIFont systemFontOfSize:17];
    
    //属性记录
    self.rightBtn = rightButton;
    
    //设置约束
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navigationBar);
        make.right.equalTo(self.navigationBar).offset(-20);
    }];

}

-(void)viewWillAppear:(BOOL)animated
{
    //1.创建查询请求  参数:查询的实体名(相当于sql中的表格)
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"UserInfo"];
    
    //2.使用上下文查询数据
    NSArray <UserInfo *>*arr = [kHMCoreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    
    
    
    UIButton *rightButton = [self.view viewWithTag:100];
    
    if (arr.firstObject == nil) {
        
        [rightButton setTitle:@"登录/注册" forState:UIControlStateNormal];
        
        //点击登录注册的功能
        [rightButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    } else {
        [self changeNacigationItem];
    }

}

- (void)login {
    UIStoryboard *storyBoard=[UIStoryboard storyboardWithName:@"Login" bundle:nil];
    QTLoginViewController *loginVC = [storyBoard instantiateInitialViewController];
    [self presentViewController:loginVC animated:NO completion:nil];
}


- (void)changeNacigationItem {
    [self.rightBtn setTitle:@"注销" forState:UIControlStateNormal];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//注销通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
